package service

import (
	"gitea.com/wan9bo7/meituan-sdk/mtclient"
	"github.com/spf13/viper"
)

type Meituan struct {
	Client       mtclient.MeituanClient
	BusinessId   int
	AppAuthToken string
}

func NewMeituanClient(businessId int, appAuthToken string) *Meituan {
	developerId := viper.GetInt64("meituan.token.developerId")
	signKey := viper.GetString("meituan.token.signKey")
	client := mtclient.NewDefaultClient(developerId, signKey)
	return &Meituan{Client: client, BusinessId: businessId, AppAuthToken: appAuthToken}
}

// Prepare 输码验券校验
func (m *Meituan) Prepare(receiptCode string) ([]byte, error) {
	apiPath := viper.GetString("meituan.certificate.prepare.apiUrl")

	var data = make(map[string]any)
	data["receiptCode"] = receiptCode

	api, err := m.Client.InvokeApi(apiPath, m.BusinessId, m.AppAuthToken, data)

	return api, err

}

// Verify 验券
func (m *Meituan) Verify(receiptCode string) ([]byte, error) {
	apiPath := viper.GetString("meituan.certificate.verify.apiUrl")
	appShopAccountName := viper.GetString("meituan.appShopAccountName")
	appShopAccount := viper.GetString("meituan.appShopAccount")

	var data = make(map[string]any)

	data["count"] = 1
	data["receiptCode"] = receiptCode
	data["appShopAccountName"] = appShopAccountName
	data["appShopAccount"] = appShopAccount
	data["requestId"] = "default"

	return m.Client.InvokeApi(apiPath, m.BusinessId, m.AppAuthToken, data)

}

// Cancel 撤销验券
// 10分钟内有效
func (m *Meituan) Cancel(receiptCode, dealId string) ([]byte, error) {
	apiPath := viper.GetString("meituan.certificate.cancel.apiUrl")
	appShopAccountName := viper.GetString("meituan.appShopAccountName")
	appShopAccount := viper.GetString("meituan.appShopAccount")

	var data = make(map[string]any)

	data["receiptCode"] = receiptCode
	data["appShopAccountName"] = appShopAccountName
	data["appShopAccount"] = appShopAccount
	data["dealId"] = dealId

	return m.Client.InvokeApi(apiPath, m.BusinessId, m.AppAuthToken, data)
}

// Get 查询已验券信息
func (m *Meituan) Get(receiptCode string) ([]byte, error) {
	apiPath := viper.GetString("meituan.certificate.get.apiUrl")

	var data = make(map[string]any)
	data["receiptCode"] = receiptCode

	return m.Client.InvokeApi(apiPath, m.BusinessId, m.AppAuthToken, data)
}
